package io.renren.service.repair.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.dao.repair.RepairInfoDao;
import io.renren.dto.repair.RepairInfoDTO;
import io.renren.dto.repair.RepairTaskDTO;
import io.renren.entity.repair.RepairInfoEntity;
import io.renren.entity.repair.RepairTaskEntity;
import io.renren.service.repair.RepairInfoService;
import io.renren.service.repair.RepairTaskService;
import io.renren.vo.RepairInfoReqVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 报修信息表
 *
 * @author dio 167762802@QQ.com
 * @since 1.0.0 2025-04-12
 */
@Slf4j
@Service
public class RepairInfoServiceImpl extends CrudServiceImpl<RepairInfoDao, RepairInfoEntity, RepairInfoDTO> implements RepairInfoService {

    @Resource
    private RepairInfoDao repairInfoDao;

    @Resource
    private RepairTaskService repairTaskService;
    @Override
    public QueryWrapper<RepairInfoEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<RepairInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(RepairInfoReqVO repairInfoReqVO, Long userId) {
        try {
            // 获取文件存储根目录
            String rootPath = "D:/upload/repair/";
            // 根据用户ID创建子目录
            String userPath = userId + "/";

            // 创建目录
            File userDir = new File(rootPath+userPath);
            if (!userDir.exists()) {
                userDir.mkdirs();
            }

            // 处理文件上传
            String fileUrls = "";
            if (repairInfoReqVO.getFiles() != null && repairInfoReqVO.getFiles().length > 0) {
                List<String> urlList = new ArrayList<>();
                for (MultipartFile file : repairInfoReqVO.getFiles()) {
                    if (!file.isEmpty()) {
                        // 生成文件名：UUID + 原文件扩展名
                        String originalFilename = file.getOriginalFilename();
                        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                        String fileName = UUID.randomUUID().toString() + fileExtension;

                        // 保存文件
                        File dest = new File(rootPath + userPath +"/"+ fileName);
                        file.transferTo(dest);

                        // 保存文件URL
                        urlList.add(userPath + fileName);
                    }
                }

                // 将多个文件URL用逗号分隔存储
                fileUrls = String.join(",", urlList);
            }

            RepairInfoEntity repairInfo = new RepairInfoEntity();
            repairInfo.setContent(repairInfoReqVO.getContent());
            repairInfo.setUserId(userId);
//           待审核状态
            repairInfo.setStatus(0);
            repairInfo.setImages(fileUrls);
            repairInfo.setLocation(repairInfoReqVO.getLocation());
            repairInfo.setContactPhone(repairInfoReqVO.getContactPhone());
            repairInfo.setContactName(repairInfoReqVO.getContactName());
            repairInfoDao.insert(repairInfo);

//          插入任务
            RepairTaskDTO repairTaskDTO = new RepairTaskDTO();
            repairTaskDTO.setRepairId(repairInfo.getId());
//            待处理
            repairTaskDTO.setStatus(0);
            repairTaskService.save(repairTaskDTO);
        } catch (Exception e) {
            log.error("保存维修信息失败", e);
            throw new RuntimeException("保存维修信息失败");
        }
    }

    @Override
    public List<RepairInfoEntity> getListByUserId(Long userId) {
        if (userId != null) {
            return repairInfoDao.selectList(new LambdaQueryWrapper<RepairInfoEntity>().eq(RepairInfoEntity::getUserId, userId));
        }
        return new ArrayList<>();
    }
    
    /**
     * 根据ID获取工单详情
     * @param id 工单ID
     * @return 工单详情实体
     */
    @Override
    public RepairInfoEntity getById(Long id) {
        if (id == null) {
            return null;
        }
        return repairInfoDao.selectById(id);
    }
}